const crypto = require("crypto");

module.exports = {
  // 解密算法 —— 根据微信官方文档提示来编写
  decryptByAES: (encryptedData, sessionKey, iv, appid) => {
    const encrypted_data = Buffer.from(encryptedData, "base64"),
      session_key = Buffer.from(sessionKey, "base64"),
      _iv = Buffer.from(iv, "base64");
    let decoded;
    try {
      // 解密
      const decipher = crypto.createDecipheriv("aes-128-cbc", session_key, _iv);

      // 设置自动 padding 为 true，删除填充补位
      decipher.setAutoPadding(true);
      decoded = decipher.update(encrypted_data, "binary", "utf8");
      decoded += decipher.final("utf8");
      decoded = JSON.parse(decoded);
    } catch (error) {
      throw new Error("Illegal Buffer");
    }
    if (decoded.watermark.appid !== appid) {
      console.log(4);
      throw new Error("Illegal Buffer");
    }
    return decoded;
  },

  encryptSha1: (data) => {
    return crypto.createHash("sha1").update(data, "utf8").digest("hex");
  },
};
